package com.xin.springcloudquartz.controller;

import com.xin.springcloudquartz.dataobject.Event;
import com.xin.springcloudquartz.dto.PageResult;
import com.xin.springcloudquartz.enums.EventStatusEnum;
import com.xin.springcloudquartz.form.EventForm;
import com.xin.springcloudquartz.service.EventService;
import com.xin.springcloudquartz.utils.*;
import com.xin.springcloudquartz.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class QuartzController {

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    @Autowired
    private EventService eventService;

    /**
     * 创建新事件
     * @param eventForm
     * @return
     * @throws SchedulerException
     * @throws ParseException
     */
    @PostMapping("/add")
    public ResultVO add(@RequestBody(required = false) EventForm eventForm) throws SchedulerException, ParseException {
        String date = eventForm.getTime();
        if (StringUtils.isEmpty(date)){
              log.info("时间不能为空");
            return ResultVOUtils.error(1, "创建事件失败!");
        }
        date = date.replace("T", " ");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date parse = format.parse(date);
        eventForm.setTime(format.format(parse));
        Date currentTime = new Date();
        if (parse.getTime() <= currentTime.getTime()) {
            log.info("【创建事件】不能是过去的时间");
            return ResultVOUtils.error(1, "创建事件失败!");
        }
        Map<String, Object> map = new HashMap<>();
        String eventId = KeyUtil.genUniqueKey().substring(6);  //事件ID
        map.put("eventId", eventId);
        map.put("date", parse.toString());
        Event event = new Event();
        BeanUtils.copyProperties(eventForm, event);
        event.setId(eventId);
        log.info("result={}",JsonUtil.toJson(eventForm));
        Event event1 = eventService.create(event);
        if (ObjectUtils.isEmpty(event1)) {
            log.info("【创建事件】创建失败!");
            return ResultVOUtils.error(1, "创建事件失败!");
        }
        //创建事件
        MessageUtils.create(eventId, CronDateUtils.getCron(parse), scheduler, map);

        return ResultVOUtils.success(event1);
    }

    /**
     * 修改事件
     * @param eventForm
     * @return
     */
    @PostMapping("/update")
    public ResultVO update(@RequestBody(required = false)EventForm eventForm,
                           @RequestParam(name = "id") String id) throws Exception {
        //查询是否存在
        Event event = eventService.findOne(id);
        //不存在
        if (ObjectUtils.isEmpty(event)){
                log.info("【修改事件】该事件不存在! id={}",id);
                return ResultVOUtils.error(1,"该事件不存在!");
        }
        String date=eventForm.getTime();
        if (StringUtils.isEmpty(date)){
            log.info("时间不能为空");
            return ResultVOUtils.error(1, "创建事件失败!");
        }
        date=date.replace("T"," ");
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date parse = format.parse(date);
        eventForm.setTime(format.format(parse));
        Date now=new Date();
        if (parse.getTime()<=now.getTime()){
            log.info("【修改事件】事件不能为过去的时间!");
            return ResultVOUtils.error(1,"时间不能为过去的时间");
        }
        String cron = CronDateUtils.getCron(parse);   //date转cron字符串
        //确定是否是执行过的
        //还没执行
        if (event.getStatus()== EventStatusEnum.START.getCode()){
            //修改Quartz
            MessageUtils.update(id,cron,scheduler);
            BeanUtils.copyProperties(eventForm,event);
            event.setStatus(EventStatusEnum.START.getCode());
            event.setId(id);
            Event update = eventService.update(event);
            if (ObjectUtils.isEmpty(update)){
                  log.info("【修改事件】修改失败! id={}",id);
                  return ResultVOUtils.error(1,"修改失败!");
            }

            return ResultVOUtils.success(update);
        }
        //执行了的，重新创建事件
        Map<String, Object> map = new HashMap<>();
        map.put("eventId", event.getId());
        map.put("date", parse.toString());
        Event news = new Event();
        BeanUtils.copyProperties(eventForm, news);
        news.setId(event.getId());
        news.setTime(format.format(parse));
        news.setStatus(EventStatusEnum.START.getCode());
        Event event1 = eventService.update(news);
        MessageUtils.create(event1.getId(),CronDateUtils.getCron(parse),scheduler,map);
        if (ObjectUtils.isEmpty(event1)) {
            log.info("【创建事件】创建失败!");
            return ResultVOUtils.error(1, "创建事件失败!");
        }

        return ResultVOUtils.success(event1);
    }

    /**
     * 删除事件
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public ResultVO delete(@RequestParam(name = "id",defaultValue = "")String id){
        boolean delete = eventService.delete(id);
        if (!delete){
            log.info("【删除事件】删除失败!");
            return ResultVOUtils.error(1,"删除失败!");
        }
        return ResultVOUtils.success();
    }

    /**
     * 查询某个事件
     * @param id
     * @return
     */
    @GetMapping("/findOne")
    public ResultVO findOne(@RequestParam(name = "id",defaultValue = "")String id){
        Event event = eventService.findOne(id);
        if (ObjectUtils.isEmpty(event)){
            return ResultVOUtils.error(1,"该事件不存在!");
        }
        return ResultVOUtils.success(event);
    }

    /**
     * 查询某人的全部事件
     * @param openId
     * @param pageable
     * @return
     */
    @GetMapping("/findAll")
    public ResultVO findAll(@RequestParam(name = "openId",defaultValue = "")String openId,
                            @PageableDefault(page = 1,size = 10)Pageable pageable){
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");
        PageRequest pageRequest=new PageRequest(pageable.getPageNumber()-1,pageable.getPageSize(),sort);
        PageResult pageResult = eventService.findAll(openId, pageRequest);
        return ResultVOUtils.success(pageResult);
    }

}
